"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 防篡改
Case Name   : 三权分立打开时验证普通超级用户（createuser）可以锁定和解锁除操作系统超级用户之外的其他用户
Create At   : 2022-03-10
Owner       : opentestcase041
Description :
    1.设置参数并重启数据库enableSeparationOfDuty=on
    2.创建不同权限用户
    3.切换具有createrole属性的普通超级用户锁定其他用户
    4.不同权限用户连接数据库,验证用户被锁定
    5.初始用户锁定用户
    6.切换具有createrole属性的普通超级用户解锁用户
    7.解锁后不同权限用户登录数据库验证用户是否被解锁
    8.清理环境
Expect      :
    1.成功
    2.成功
    3.操作系统超级用户之外的其他用户锁定成功
    4.操作系统超级用户之外的其他用户被锁定
    5.成功
    6.操作系统超级用户之外的其他用户解锁成功
    7.操作系统超级用户之外的其他用户被解锁
    8.成功
History     : 
"""

import os
import unittest
from yat.test import macro
from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Common import Common
from testcase.utils.Logger import Logger


class ModifyCase(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.common = Common()
        self.user_name = 'u_security_userlockprivilege_0003'
        self.user_privileges = {f'{self.user_name}_sys': 'sysadmin',
                                f'{self.user_name}_audit': 'auditadmin',
                                f'{self.user_name}_create': 'createrole',
                                f'{self.user_name}_create_01': 'createrole',
                                f'{self.user_name}_noruser': ''}
        self.default_value = self.common.show_param('enableSeparationOfDuty')

    def test_security(self):
        text = '-----step1：设置参数并重启数据库enableSeparationOfDuty=on; ' \
               'expect:成功-----'
        self.log.info(text)
        mod_msg = \
            self.primary_sh.execute_gsguc('set',
                                          self.constant.GSGUC_SUCCESS_MSG,
                                          'enableSeparationOfDuty=on')
        self.log.info(mod_msg)
        self.assertTrue(mod_msg, '执行失败:' + text)
        restart_msg = self.primary_sh.restart_db_cluster()
        self.log.info(restart_msg)
        status = self.primary_sh.get_db_cluster_status()
        self.assertTrue("Degraded" in status or "Normal" in status,
                        '执行失败:' + text)

        text = '-----step2：创建不同权限用户 expect:成功-----'
        self.log.info(text)
        for user, privilege in self.user_privileges.items():
            create_cmd = f"drop user if exists {user} cascade; " \
                        f"create user {user} {privilege} " \
                        f"password '{macro.PASSWD_REPLACE}' ; "
            msg = self.primary_sh.execut_db_sql(create_cmd)
            self.log.info(msg)
            self.assertIn(self.constant.CREATE_ROLE_SUCCESS_MSG, msg,
                          '执行失败:' + text)

        text = '-----step3：切换具有createrole属性的普通超级用户锁定用户 ' \
               'expect:操作系统超级用户之外的其他用户锁定成功-----'
        self.log.info(text)
        user_lock = [f'{self.user_name}_sys', f'{self.user_name}_noruser',
                     f'{self.user_name}_create_01', f'{self.user_name}_audit']
        for user in user_lock:
            create_cmd = f'''set role {self.user_name}_create  password 
                        '{macro.PASSWD_REPLACE}';
                        alter user {user} account lock;'''
            msg = self.primary_sh.execut_db_sql(create_cmd)
            self.log.info(msg)
            if user in {f'{self.user_name}_noruser'}:
                self.assertIn(self.constant.ALTER_ROLE_SUCCESS_MSG, msg,
                              '执行失败:' + text)
                self.assertIn(self.constant.SET_SUCCESS_MSG, msg,
                              '执行失败:' + text)
            else:
                self.assertIn(self.constant.PERMISSION_DENY_MSG, msg,
                              '执行失败:' + text)
                self.assertIn(self.constant.SET_SUCCESS_MSG, msg,
                              '执行失败:' + text)

        text = '----step4:不同权限用户连接数据库,验证用户被锁定 ' \
               'expect:操作系统超级用户之外的其他用户锁定成功----'
        self.log.info(text)
        sql_cmd = f'''select user;'''
        self.log.info(sql_cmd)
        for user in user_lock:
            msg = self.primary_sh.execut_db_sql(
                sql_cmd, sql_type=f' -U {user} -W {macro.PASSWD_REPLACE}')
            self.log.info(msg)
            if user in {f'{self.user_name}_noruser'}:
                self.assertIn(self.constant.ACCOUNT_LOCKED_TYPE, msg,
                              "执行失败:" + text)
            else:
                self.assertIn(user, msg, "执行失败:" + text)

        text = '-----step5：初始用户锁定其他用户 expect:成功-----'
        self.log.info(text)
        for user in user_lock:
            create_cmd = f'''alter user {user} account lock;'''
            msg = self.primary_sh.execut_db_sql(create_cmd)
            self.log.info(msg)
            self.assertIn(self.constant.ALTER_ROLE_SUCCESS_MSG, msg,
                          '执行失败:' + text)

        text = '-----step6：切换具有createrole属性的普通超级用户解锁用户 ' \
               'expect:操作系统超级用户之外的其他用户解锁成功-----'
        self.log.info(text)
        user_lock = [f'{self.user_name}_sys', f'{self.user_name}_noruser',
                     f'{self.user_name}_create_01', f'{self.user_name}_audit']
        for user in user_lock:
            create_cmd = f'''set role {self.user_name}_create  password 
                            '{macro.PASSWD_REPLACE}';
                            alter user {user} account unlock;'''
            msg = self.primary_sh.execut_db_sql(create_cmd)
            self.log.info(msg)
            if user in {f'{self.user_name}_noruser'}:
                self.assertIn(self.constant.ALTER_ROLE_SUCCESS_MSG, msg,
                              '执行失败:' + text)
            else:
                self.assertIn(self.constant.PERMISSION_DENY_MSG, msg,
                              '执行失败:' + text)
            self.assertIn(self.constant.SET_SUCCESS_MSG, msg,
                          '执行失败:' + text)

        text = '----step7:解锁后不同权限用户登录数据库验证用户是否被解锁 ' \
               'expect:操作系统超级用户之外的其他用户被解锁----'
        self.log.info(text)
        sql_cmd = f'''select user;'''
        self.log.info(sql_cmd)
        for user in user_lock:
            msg = self.primary_sh.execut_db_sql(
                sql_cmd, sql_type=f' -U {user} -W {macro.PASSWD_REPLACE}')
            self.log.info(msg)
            if user in {f'{self.user_name}_noruser'}:
                self.assertIn(f'{self.user_name}_noruser', msg,
                              "执行失败:" + text)
            else:
                self.assertIn(self.constant.ACCOUNT_LOCKED_TYPE, msg,
                              "执行失败:" + text)

    def tearDown(self):
        text = '----step8:清理环境 expect:成功----'
        self.log.info(text)
        self.log.info('删除用户')
        drop_msg = []
        for user in self.user_privileges.keys():
            drop_cmd = f"drop user {user} cascade; "
            msg = self.primary_sh.execut_db_sql(drop_cmd)
            self.log.info(msg)
            drop_msg.append(msg)
        self.log.info('恢复参数默认值')
        mod_msg1 = \
            self.primary_sh.execute_gsguc('set',
                                          self.constant.GSGUC_SUCCESS_MSG,
                                          f'enableSeparationOfDuty='
                                          f'{self.default_value}')
        self.log.info(mod_msg1)
        restart_msg = self.primary_sh.restart_db_cluster()
        self.log.info(restart_msg)
        status = self.primary_sh.get_db_cluster_status()
        self.assertEqual(5,
                         drop_msg.count(self.constant.DROP_ROLE_SUCCESS_MSG),
                         '执行失败:' + text)
        self.assertTrue("Degraded" in status or "Normal" in status,
                        '执行失败:' + text)
        self.assertTrue(mod_msg1, '执行失败:' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
